//
//  SearchViewController.m
//  IT爱好者
//
//  Created by dllo on 15/10/7.
//  Copyright © 2015年 Fan. All rights reserved.
//

#import "SearchViewController.h"
#import "Header.h"
#import "detaiPageForPoductionTableViewCell.h"
#import "CFNetworkFromAFNetworking.h"
#import "DetailimageInformationModel.h"
#import "DataModel.h"
#import "ButtonImageView.h"
#import "SortdeList.h"
#import "SectionTitleModel.h"
#import "MJRefresh.h"
#import "ForMJRefreshModel.h"
#import "ReplaceSearchBarView.h"
#import "SearchBarViewController.h"
#import "WebViewController.h"
#import "DataBaseManager.h"
#import "FavoriteWapPage.h"
#import "MBProgressHUD.h"
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, retain)UIView *topView;
@property(nonatomic, retain)UIView *lineView;
@property(nonatomic, retain)UITableView *tabeleView;
@property(nonatomic, retain)NSMutableArray *dataSourceArray;
@property(nonatomic, assign)CGPoint contentPoint;
@property(nonatomic, retain)NSMutableArray *hotArray;
@property(nonatomic, retain)NSMutableArray *priceArray;
@property(nonatomic, retain)UITableView *sortedTableView;
@property(nonatomic, retain)NSMutableArray *sortedArray;
@property(nonatomic, retain)NSMutableArray *BarDatawSourceArray;
@property(nonatomic, retain)UITableView *priceAndHotTableView;
@property(nonatomic, retain)UITableView *priceTableView;
@property(nonatomic, retain)UILabel *pageLabel;

@property(nonatomic, retain)NSString *priceIdFlag;
@property(nonatomic, retain)NSString *orderByFlag;
@property(nonatomic, retain)NSString *manuidFlag;

@property(nonatomic, assign)NSInteger page;
@property(nonatomic, assign)NSInteger totlePage;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, assign)NSInteger flag1;

@property(nonatomic, retain)ForMJRefreshModel *refreshModel;
@property(nonatomic, retain)ReplaceSearchBarView *replaceSBView;

@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, retain)UILabel *noticeLabel;
@end

@implementation SearchViewController

-(void)loadView
{
    [super loadView];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.sortedArray = [NSMutableArray array];
    self.BarDatawSourceArray = [NSMutableArray array];
    self.dataSourceArray = [NSMutableArray array];
    self.priceArray = [NSMutableArray array];
    _priceIdFlag = @"noPrice";
    _manuidFlag = nil;
    _orderByFlag = nil;
    _page = 1;
    _totlePage = 1;
    _refreshModel = [[ForMJRefreshModel alloc]init];
    _refreshModel.flag = 0;
    
    
    [self getdataSource];
    [self getBarDataSource];
    [self getPricearray];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BackgroundColor;
#pragma mark - 顶部视图构造
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40 * FitHeight)];
    _topView.backgroundColor = [UIColor colorWithRed:0.43 green:0.35 blue:0.26 alpha:.1];
    
    //顶部视图上加button
    NSArray *titleArr = [NSArray arrayWithObjects:@"热门",@"价格",@"品牌", nil];
    for (NSInteger i = 0 ; i < 3; i++) {
        ButtonImageView *buttonImageView = [[ButtonImageView alloc]initWithFrame:CGRectMake(65 * FitWidth + i * 100, 10, 30 * FitWidth, 20 * FitHeight)];
        buttonImageView.button.tag = 1000 * (i + 1);
        [buttonImageView.button setTitle:titleArr[i] forState:UIControlStateNormal];
        [buttonImageView.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        if (i < 2) {
            buttonImageView.imageView.image = [UIImage imageNamed:@"sanjiao"];
        }else{
            buttonImageView.imageView.image = [UIImage imageNamed:@"loudou"];
        }
        
        [_topView addSubview:buttonImageView];
    }
    [self.view addSubview:_topView];
    
#pragma mark 页面数据显示
    _tabeleView = [[UITableView alloc]initWithFrame:CGRectMake(_topView.frame.origin.x, _topView.frame.origin.y + _topView.frame.size.height, _topView.frame.size.width, ScreenHeight - (64 + 49) * FitHeight - _topView.frame.size.height)];
    _tabeleView.delegate = self;
    _tabeleView.dataSource = self;
    _tabeleView.showsHorizontalScrollIndicator = NO;
    _tabeleView.showsVerticalScrollIndicator = NO;
    _tabeleView.backgroundColor = BackgroundColor;
    _tabeleView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tabeleView];
    
#pragma mark 品牌筛选的显示
    _sortedTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40 * FitHeight, ScreenWidth, 0)];
    _sortedTableView.delegate = self;
    _sortedTableView.dataSource = self;
    _sortedTableView.showsHorizontalScrollIndicator = NO;
    _sortedTableView.showsVerticalScrollIndicator = NO;
    _sortedTableView.backgroundColor = BackgroundColor;
    _sortedTableView.tableFooterView = [[UIView alloc]init];
    //给排序表添加手势 向右滑动消失
    UISwipeGestureRecognizer *tap1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipAction)];
    [_sortedTableView addGestureRecognizer:tap1];
    [self.view addSubview:_sortedTableView];
    
#pragma mark 热门筛选的显示
    _priceAndHotTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0) style:UITableViewStylePlain];
    _priceAndHotTableView.delegate = self;
    _priceAndHotTableView.dataSource = self;
    _priceAndHotTableView.showsHorizontalScrollIndicator = NO;
    _priceAndHotTableView.showsVerticalScrollIndicator = NO;
    _priceAndHotTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_priceAndHotTableView];

    
#pragma mark 价格筛选的显示
    _priceTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40 * FitHeight, ScreenWidth, 0)];
    _priceTableView.delegate = self;
    _priceTableView.dataSource = self;
    _priceTableView.showsHorizontalScrollIndicator = NO;
    _priceTableView.showsVerticalScrollIndicator = NO;
    _priceTableView.backgroundColor = BackgroundColor;
    _priceTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_priceTableView];


#pragma mark 制作页面显示的label
    _pageLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _pageLabel.textAlignment = 1;
    _pageLabel.backgroundColor = [UIColor colorWithRed:0.87 green:0.84 blue:0.83 alpha:.5];
    _pageLabel.layer.cornerRadius = 10;
    _pageLabel.font = [UIFont systemFontOfSize:10];
    _pageLabel.text = [NSString stringWithFormat:@"第 %ld 页", _page];
    [self.view addSubview:_pageLabel];

    
#pragma mark 提示框
    self.noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200) / 2, 80, 200, 20)];
    _noticeLabel.textAlignment = 1;
    [self.view addSubview:_noticeLabel];
    
#pragma mark MJ首页下拉刷新 上拉加载
    _tabeleView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSourceArray removeAllObjects];
        [_tabeleView reloadData];
        _page = 1;
        switch (_refreshModel.flag) {
            case 0:
            {[self getdataSource];}
                break;
            case 1:
            {[self reloadPage:_refreshModel.productLM];}
                break;
            case 2:
            {[self getListArr:_refreshModel.productLM];}
                break;
            case 3:
            {[self getpriceSortdeArr:_refreshModel.productLM];}
                break;
            case 4:
            {[self loadPaihangbang];}
                break;
                
            default:
                break;
        }
        
    }];

    _tabeleView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _page ++;
        switch (_refreshModel.flag) {
            case 0:
            {[self getdataSource];}
                break;
            case 1:
            {[self reloadPage:_refreshModel.productLM];}
                break;
            case 2:
            {[self getListArr:_refreshModel.productLM];}
                break;
            case 3:
            {[self getpriceSortdeArr:_refreshModel.productLM];}
                break;
            case 4:
            {[self loadPaihangbang];}
                break;
                
            default:
                break;
        }

    }];
    
#pragma 制作假搜索栏 点击跳入真的
    _replaceSBView = [[ReplaceSearchBarView alloc]initWithFrame:CGRectMake(0, 0, 265, 25)];
    _replaceSBView.layer.cornerRadius = 5;
    self.navigationItem.titleView = _replaceSBView;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [_replaceSBView addGestureRecognizer:tap];
    
#pragma mark 菊花
    _HUD = [MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    _HUD.backgroundColor = [UIColor clearColor];
    _HUD.labelText = @"正在刷新";
    _HUD.detailsLabelText = @"请耐心等待";
    
    //夜间模式的监听者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(colorChange) name:@"colorChange" object:nil];
}

#pragma mark - 夜间模式 监听到变化后采取的措施
- (void )colorChange
{
    self.view.backgroundColor = BackgroundColor;
    _tabeleView.backgroundColor = BackgroundColor;
    _priceAndHotTableView.backgroundColor = BackgroundColor;
    [_priceAndHotTableView reloadData];
    _priceTableView.backgroundColor = BackgroundColor;
    [_priceTableView reloadData];
    _sortedTableView.backgroundColor = BackgroundColor;
    [_sortedTableView reloadData];
    [_tabeleView reloadData];
    
}

//假搜索栏tap事件
-(void)tapAction
{
    SearchBarViewController *sbVC = [[SearchBarViewController alloc]init];
    sbVC.keyID = 2;
    sbVC.modalTransitionStyle = 2;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:sbVC];
    [self presentViewController:nav animated:YES completion:NULL];
    //[self presentViewController:sbVC animated:YES completion:nil];
}
//排序表tap事件
- (void)swipAction
{
    _sortedTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
}

#pragma mark - 按钮点击事件
//点击按钮事件
- (void)buttonAction:(UIButton *)sender
{
    switch (sender.tag) {
        case 1000:
        {
            _sortedArray = nil;
            _priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
            _flag1 = 0;
            [self getHotarray];
            self.sortedArray = _hotArray;
            [_priceAndHotTableView reloadData];
            _sortedTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
            if (_flag == 0) {
                [UIView animateWithDuration:.5 animations:^{
                    _priceAndHotTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 360 * FitHeight);
                    _flag = 1;
                }];
            }else{
                _priceAndHotTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
                _flag = 0;
            }
        }
            break;
        case 2000:
        {
            _sortedArray = nil;
            
            self.sortedArray = _priceArray;
            [_priceTableView reloadData];
            _sortedTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
            _flag = 0;
            _priceAndHotTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
            if (_flag1) {
                _priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
                _flag1 = 0;
            }else{
                [UIView animateWithDuration:.5 animations:^{
                    _priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 360 * FitHeight);
                    _flag1 = 1;
                }];
            }
            
        }
            break;
        case 3000:
        {
            _sortedArray = nil;
            _priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
            _priceAndHotTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
            _flag = 0;
            _flag1 = 0;
            //上页传来分组数组就用
            if (self.allProductArray != nil) {
                ////NSLog(@"%@", _allProductArray);
                NSMutableArray *sortArr = [NSMutableArray arrayWithArray:_allProductArray];
                [sortArr removeObjectAtIndex:0];
                self.sortedArray = sortArr;
                [_sortedTableView reloadData];
            }else{
                //没传来就去创造
                _HUD.hidden = NO;
                [self getBarDataSource];
            }
            _sortedTableView.frame = CGRectMake(ScreenWidth, 0, 0, ScreenHeight - 113 * FitHeight);
            [UIView animateWithDuration:.5 animations:^{
                _sortedTableView.frame = CGRectMake(100 * FitWidth, 0, ScreenWidth - 100 * FitWidth, ScreenHeight - 113 * FitHeight);
            }];
            
        }
            break;
        default:
            break;
    }
    
}




#pragma mark - 滚动tableView关于筛选栏和页码label的上拉下滑
//开始拉 记坐标
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == _tabeleView) {
        _contentPoint = _tabeleView.contentOffset;
        _priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
        _priceAndHotTableView.frame =CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
        _sortedTableView.frame = CGRectMake(0, 40 * FitHeight, 0, ScreenHeight);
        _flag = 0;
        _flag1 = 0;
    }
}
//滚动大于或小于值 收回/出现
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _tabeleView) {
        CGPoint point = _tabeleView.contentOffset;
        if (_contentPoint.y -  point.y <= - 10) {
            [UIView animateWithDuration:.2 animations:^{
                _topView.frame = CGRectMake(0, 0, ScreenWidth, 0);
                _tabeleView.frame = CGRectMake(0,0, ScreenWidth, ScreenHeight - (64 + 49) * FitHeight);
            }];

        }
        if (_contentPoint.y -  point.y >= 10) {
            [UIView animateWithDuration:.2 animations:^{
                _topView.frame = CGRectMake(0, 0, ScreenWidth, 40 * FitHeight);
                _tabeleView.frame = CGRectMake(_topView.frame.origin.x, _topView.frame.origin.y + _topView.frame.size.height, _topView.frame.size.width, ScreenHeight - (64 + 49) * FitHeight - _topView.frame.size.height);
            }];
        }
        //_sortedTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
        _pageLabel.frame = CGRectMake(166 * FitWidth, 530 * FitHeight, 40 * FitWidth, 20 * FitHeight);
        
    }
}
//滚动停止label消失
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _tabeleView) {
        _pageLabel.frame = CGRectZero;
        //_priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
    }
}

#pragma mark - 获取热门列表
- (void)getHotarray
{
    SectionTitleModel *stM1 = [[SectionTitleModel alloc]init];
    stM1.detaileArray = [NSMutableArray array];

    /**三星:id=98 手机subid=57(cateid)
http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&manuId=98&noParam=1&num=20&orderBy=4&page=1&priceId=3000&subcateId=57
     */
    NSMutableArray *hotArr = [NSMutableArray arrayWithObjects:@"热门", @"最新", @"价高", @"价低", @"点评", @"销量", nil];
    NSMutableArray *orderIdArr = [NSMutableArray arrayWithObjects:@"renmende", @"14", @"4", @"3", @"5", @"11", nil];
    for (NSInteger i = 0; i < hotArr.count; i++) {
        ProductListModel *plM = [[ProductListModel alloc]init];
        plM.name = hotArr[i];
        plM.cateId = _PLM.cateId;
        plM.Id = _PLM.Id;
        plM.picUrl = nil;
        plM.orderById = orderIdArr[i];
        [stM1.detaileArray addObject:plM];
    }
    stM1.sectionTitle = @"";
    stM1.subId = _PLM.cateId;
    self.hotArray = [NSMutableArray arrayWithObjects:stM1, nil];
}

#pragma mark 获取价格列表
- (void)getPricearray
{
    if (_PLM.isPDClassM == YES) {
        self.priceArray = [NSMutableArray array];
        SectionTitleModel *stM2 = [[SectionTitleModel alloc]init];
        stM2.detaileArray = [NSMutableArray array];
        NSString *urlstring = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_SearchParam_V1&subcateId=%@&manuId=", _PLM.Id];
        [CFNetworkFromAFNetworking askObjectByURLString:urlstring BodyString:nil WithObjectBlock:^(id object) {
            NSArray *arra = [[object objectForKey:@"price"] objectForKey:@"list"];
            NSMutableArray *priceArr = [NSMutableArray array];
            for (NSDictionary *dic in arra) {
                ProductListModel *plM = [[ProductListModel alloc]init];
                [plM setValuesForKeysWithDictionary:dic];
                [stM2.detaileArray addObject:plM];
                [priceArr addObject:plM];
            }
            self.priceArray = [NSMutableArray arrayWithObjects: stM2, nil];
            
            
        }];
    }
    if (_PLM.isPDClassM == NO) {
        self.priceArray = [NSMutableArray array];
        SectionTitleModel *stM2 = [[SectionTitleModel alloc]init];
        stM2.detaileArray = [NSMutableArray array];
        stM2.sectionTitle = nil;
        NSString *urlstring = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_SearchParam_V1&subcateId=%@&manuId=", _PLM.cateId];
        [CFNetworkFromAFNetworking askObjectByURLString:urlstring BodyString:nil WithObjectBlock:^(id object) {
            NSArray *arra = [[object objectForKey:@"price"] objectForKey:@"list"];
            NSMutableArray *priceArr = [NSMutableArray array];
            for (NSDictionary *dic in arra) {
                ProductListModel *plM = [[ProductListModel alloc]init];
                [plM setValuesForKeysWithDictionary:dic];
                [stM2.detaileArray addObject:plM];
                [priceArr addObject:plM];
            }
            self.priceArray = [NSMutableArray arrayWithObjects: stM2, nil];
            self.sortedArray = _priceArray;
            [_priceTableView reloadData];
        }];
    }
    
}

#pragma mark - 关于cell的
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _sortedTableView || tableView == _priceAndHotTableView || tableView == _priceTableView) {
        return _sortedArray.count;
    }else return 1;
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == _sortedTableView || tableView == _priceAndHotTableView || tableView == _priceTableView) {
        return [_sortedArray[section] sectionTitle];
    }else{
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tabeleView) {
        return 100 * FitHeight;
    }else if (tableView == _sortedTableView || tableView == _priceAndHotTableView || tableView == _priceTableView){
        return 60;
    }return 0;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tabeleView) {
        return _dataSourceArray.count;
    }else if (tableView == _sortedTableView || tableView == _priceAndHotTableView || tableView == _priceTableView){
        return [[_sortedArray[section] detaileArray] count];
    }return 0;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tabeleView) {
        static NSString *identifier = @"cell";
        detaiPageForPoductionTableViewCell *ptVCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!ptVCell) {
            ptVCell = [[detaiPageForPoductionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        ////NSLog(@"开始给页面赋值");
        ptVCell.dataModel = _dataSourceArray[indexPath.row];
        return ptVCell;
    }
    if (tableView == _sortedTableView){
        static NSString *identifer1 = @"cell1";
        SortdeList *slCell = [tableView dequeueReusableCellWithIdentifier:identifer1];
        if (!slCell) {
            slCell = [[SortdeList alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer1];
        }
        slCell.titleLabel.text = [[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row] name];
        slCell.backgroundColor = [UIColor colorWithRed:0.99 green:0.99 blue:0.99 alpha:1];
        return slCell;
    }
    if (tableView == _priceAndHotTableView){
        static NSString *identifier2 = @"cell2";
        SortdeList *slCell2 = [tableView dequeueReusableCellWithIdentifier:identifier2];
        if (!slCell2) {
            slCell2 = [[SortdeList alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier2];
        }
        slCell2.titleLabel.text = [[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row] name];
        slCell2.backgroundColor = [UIColor colorWithRed:0.99 green:0.99 blue:0.99 alpha:1];
        return slCell2;
    }
    if (tableView == _priceTableView) {
        static NSString *identifier3 = @"cell3";
        SortdeList *slCell3 = [tableView dequeueReusableCellWithIdentifier:identifier3];
        if (!slCell3) {
            slCell3 = [[SortdeList alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier3];
        }
        slCell3.titleLabel.text = [[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row] name];
        slCell3.backgroundColor = [UIColor colorWithRed:0.99 green:0.99 blue:0.99 alpha:1];
        return slCell3;

    }
    
    return nil;

}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == _sortedTableView) {
        if (_sortedArray.count > 1) {
            NSMutableArray *sectionArray = [NSMutableArray array];
            for (SectionTitleModel *stM in _sortedArray) {
                if (stM.sectionTitle != nil) {
                    [sectionArray addObject:[stM.sectionTitle substringToIndex:1]];
                }
            }
            return sectionArray;
        }

    }
    return nil;
}

#pragma mark 点击页面收回搜索
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView != _tabeleView) {
        if (tableView == _sortedTableView) {
            _refreshModel.flag = 1;//点击排序后flag置为1 MJ找新数据刷新
//#warning 为什么需要重新初始化数组????????????????????????????
            _HUD.hidden = NO;
            self.dataSourceArray = [NSMutableArray array];
//#warning 不过,下面直接reload一下,可以有效防止tableView重新赋值时网络卡新值没请求来的情况下点击或滑动引起的数组越界
            [_tabeleView reloadData];
            if (_PLM.isPDClassM == NO) {
                if (indexPath.section < 1) {
                    _refreshModel.flag = 4;
                    [self loadPaihangbang];
                }else{
                    [self reloadPage:[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row]];
                }
            }
            
            if (_PLM.isPDClassM == YES) {
                [self reloadPage:[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row]];
            }
        }
        if (tableView == _priceAndHotTableView) {
            _refreshModel.flag = 2;
            _HUD.hidden = NO;
            self.dataSourceArray = [NSMutableArray array];
            [_tabeleView reloadData];
            if (indexPath.row == 0) {
                [self getdataSource];
                _refreshModel.flag = 0;
            }else{
                [self getListArr:[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row]];
            }
        }
        if (tableView == _priceTableView) {
            _refreshModel.flag = 3;
            self.dataSourceArray = [NSMutableArray array];
            _HUD.hidden = NO;
            [_tabeleView reloadData];
            //拼id
            [self getpriceSortdeArr:[[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row]];
        }
        _refreshModel.productLM = [[_sortedArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row];
        _page = 1;
    }
    _priceTableView.frame = CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
    _priceAndHotTableView.frame =CGRectMake(0, 40 * FitHeight, ScreenWidth, 0);
    _sortedTableView.frame = CGRectMake(0, 40 * FitHeight, 0, ScreenHeight);
    _flag = 0;
    _flag1 = 0;
    if (tableView == _tabeleView) {
#pragma mark - 点击进入web页 并用数据库记录查看过
        WebViewController *webView = [[WebViewController alloc]init];
        webView.Id = [_dataSourceArray[indexPath.row] Id];
        FavoriteWapPage *fwp = [[FavoriteWapPage alloc]init];
        fwp.title = [_dataSourceArray[indexPath.row] name];
//        NSString *urlString = [NSString stringWithFormat:@"http://wap.zol.com.cn/369/%@/index.html", [_dataSourceArray[indexPath.row] Id]];
        fwp.wapUrlString = [_dataSourceArray[indexPath.row] Id];
        [DataBaseManager creatPriceTable];
        NSArray *arr = [DataBaseManager selectPrice];
        if (arr.count > 10) {
            [DataBaseManager deleteFavoritePricePage:arr[0]];
        }
        NSMutableArray * arrTitle = [NSMutableArray array];
        for (FavoriteWapPage *fwP in arr) {
            [arrTitle addObject:fwP.title];
        }
        if (![arrTitle containsObject:fwp.title]) {
            [DataBaseManager insertFavoritePricePage:fwp];
        }
        
        [self.navigationController pushViewController:webView animated:YES];
    }
}


#pragma mark - 首页的数据请求
//产品的数据
- (void)getdataSource
{
    //判断传来的是分类的点击事件(拼产品id
    NSString *urlString = [NSString string];
    if (_PLM.isPDClassM) {
        urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&noParam=1&num=20&page=%ld&priceId=noPrice&subcateId=%@", _page, _PLM.Id];
        
    }else{//传来的是筛选的点击事件
        if ([_PLM.Id isEqualToString:@"shaixuan"]) {
            //点击筛选请求这个网址(拼cateid{父类id
            urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&noParam=1&num=20&page=%ld&priceId=noPrice&subcateId=%@", _page, _PLM.cateId];
            
            //传来的是排行榜的点击事件
        }else if ([_PLM.Id isEqualToString:@"paihangbang"]) {
            //排行请求(拼cateid
            urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?a=ProRank&c=Iphone_Top&num=20&page=%ld&subcateId=%@", _page, _PLM.cateId];
        }else{
            //传来的是产品的点击事件(拼接产品id和父类id
            urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&manuId=%@&noParam=1&num=20&page=%ld&priceId=noPrice&subcateId=%@",_PLM.Id, _page, _PLM.cateId];
        }
    }
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        DetailimageInformationModel *dinfoM = [[DetailimageInformationModel alloc]init];
        [dinfoM setValuesForKeysWithDictionary:object];
        NSArray *array = [object objectForKey:@"data"];
        if (array.count > 0) {
            for (NSDictionary *dic in array) {
                DataModel *dataM = [[DataModel alloc]init];
                [dataM setValuesForKeysWithDictionary:dic];
                [self.dataSourceArray addObject:dataM];
            }
            ////NSLog(@"产品的点击事件%ld", _dataSourceArray.count);
            [_tabeleView reloadData];
            if (_dataSourceArray.count == 0) {
                _noticeLabel.text = @"没有想要的内容";
            }else{
                _noticeLabel.text = @"";
            }
            [_tabeleView.header endRefreshing];
            [_tabeleView.footer endRefreshing];
            _HUD.hidden = YES;
            if (_page <= ([dinfoM.allNum integerValue] / 20 + 1)) {
                _pageLabel.text = [NSString stringWithFormat:@"第%ld页", _page];
            }
        }else{
            [_tabeleView.footer noticeNoMoreData];
        }
    }];
}

#pragma mark - 点击全部(排行榜)
- (void)loadPaihangbang
{
    NSString *urlString = urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&noParam=1&num=20&page=%ld&priceId=noPrice&subcateId=%@", _page, _PLM.cateId];
//    //NSLog(@"2--%@", urlString);
    if (_page <= _totlePage) {
        [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
            DetailimageInformationModel *dinfoM = [[DetailimageInformationModel alloc]init];
            [dinfoM setValuesForKeysWithDictionary:object];
            NSArray *array = [object objectForKey:@"data"];
            if (array.count > 0) {
                for (NSDictionary *dic in array) {
                    DataModel *dataM = [[DataModel alloc]init];
                    [dataM setValuesForKeysWithDictionary:dic];
                    [_dataSourceArray addObject:dataM];
                }
                ////NSLog(@"产品的点击事件%ld", _dataSourceArray.count);
                [_tabeleView reloadData];
                _HUD.hidden = YES;
                self.totlePage = ([dinfoM.allNum integerValue] / 20 + 1);
                if (_dataSourceArray.count == 0) {
                    _noticeLabel.text = @"没有想要的内容";
                }else{
                    _noticeLabel.text = @"";
                }
                [_tabeleView.header endRefreshing];
                [_tabeleView.footer endRefreshing];
                _pageLabel.text = [NSString stringWithFormat:@"第%ld页", _page];
            }
        }];
    }else{
        [_tabeleView.footer noticeNoMoreData];
    }
    
    
}


#pragma mark 没有可用数组,重新获得品牌的下拉页(分组的那种上页没传过来的)
//搜索数据(点分类时)强行将数据加载到了productListModel
-(void)getBarDataSource
{
    self.sortedArray = [NSMutableArray array];
    NSString *urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_SearchParam_V1&subcateId=%@&manuId=", _PLM.Id];
   // //NSLog(@"%@", _PLM.Id);
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        ////NSLog(@"%@", [object allKeys]);
        SectionTitleModel *sectionTM = [[SectionTitleModel alloc]init];
        sectionTM.sectionTitle = @"热门品牌";
        sectionTM.subId = @"热门";
        sectionTM.detaileArray = [NSMutableArray array];
        NSMutableArray *arrayhot = [object objectForKey:@"rankManu"];
        for (NSDictionary *dichot in arrayhot) {
            ProductListModel *productlm = [[ProductListModel alloc]init];
            [productlm setValuesForKeysWithDictionary:dichot];
            productlm.isPDClassM = YES;
            productlm.cateId = _PLM.Id;
            [sectionTM.detaileArray addObject:productlm];
        }
        //
        NSArray *arraynomal = [object objectForKey:@"abcManu"];;
        for (NSDictionary *dic in arraynomal) {
            SectionTitleModel *nomalSTM = [[SectionTitleModel alloc]init];
            nomalSTM.sectionTitle = [dic objectForKey:@"name"];
            nomalSTM.detaileArray = [NSMutableArray array];
            for (NSDictionary *dict in [dic objectForKey:@"list"]) {
                ProductListModel *prodLm = [[ProductListModel alloc]init];
                [prodLm setValuesForKeysWithDictionary:dict];
                prodLm.cateId = _PLM.Id;
                [nomalSTM.detaileArray addObject:prodLm];
            }
            nomalSTM.subId = @"nomal";
            [self.sortedArray addObject:nomalSTM];
        }
        NSComparator sortBlock = ^(id obj1, id obj2){
            SectionTitleModel *sectionTitleM1 = (SectionTitleModel *)obj1;
            SectionTitleModel *sectionTitleM2 = (SectionTitleModel *)obj2;
            if (sectionTitleM1.sectionTitle > sectionTitleM2.sectionTitle) {
                return NSOrderedDescending;
            }else{
                return NSOrderedAscending;
            }
        };
        NSArray *sortdeArr = [_sortedArray sortedArrayUsingComparator:sortBlock];
        self.sortedArray = [NSMutableArray arrayWithArray:sortdeArr];
        [self.sortedArray insertObject:sectionTM atIndex:0];
        [_sortedTableView reloadData];
        _HUD.hidden = YES;
        
    }];
}

#pragma mark 点击热门得到新数据 重载tableView
- (void)getListArr:(ProductListModel *)proLM
{
    NSString *urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&%@noParam=1&num=20&orderBy=%@&page=%ld&priceId=%@&subcateId=%@",self.manuidFlag, proLM.orderById, _page, _priceIdFlag, _PLM.cateId];
    if (_PLM.isPDClassM == YES) {
        urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&%@noParam=1&num=20&orderBy=%@&page=%ld&priceId=%@&subcateId=%@",self.manuidFlag, proLM.orderById, _page, _priceIdFlag, _PLM.Id];
    }
    ////NSLog(@"%@", urlString);
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        DetailimageInformationModel *dInfoM = [[DetailimageInformationModel alloc]init];
        [dInfoM setValuesForKeysWithDictionary:object];
        dInfoM.data = [NSArray array];
        for (NSDictionary *dic in [object objectForKey:@"data"]) {
            DataModel *dataMo = [[DataModel alloc]init];
            [dataMo setValuesForKeysWithDictionary:dic];
            [self.dataSourceArray addObject:dataMo];
        }
        _orderByFlag = proLM.orderById;
        //_tabeleView.contentOffset = CGPointZero;
        [_tabeleView reloadData];
        _HUD.hidden = YES;
        if (_dataSourceArray.count == 0) {
            _noticeLabel.text = @"没有想要的内容";
        }else{
            _noticeLabel.text = @"";
        }
        [_tabeleView.header endRefreshing];
        [_tabeleView.footer endRefreshing];
        _pageLabel.text = [NSString stringWithFormat:@"第%ld页", _page];
    }];
}

#pragma mark 点击价格 得到数据 重载tableView
-(void)getpriceSortdeArr:(ProductListModel *)plM
{
    
    NSString *manuid = nil;
    NSString *order = nil;
    //价格排序与热门排序无关所以不拼接了
    //if (_orderByFlag != nil) {
        //order = [NSString stringWithFormat:@"orderBy=%@&&", _orderByFlag];
    //}
    if (_manuidFlag != nil) {
        manuid = _manuidFlag;;
    }
    NSString *urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&%@noParam=1&num=20&%@page=%ld&priceId=%@&subcateId=%@",manuid, order, _page, plM.Id, _PLM.cateId];
    if (_PLM.isPDClassM == YES) {
        urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&%@noParam=1&num=20&%@page=%ld&priceId=%@&subcateId=%@", manuid, order,_page, plM.Id, _PLM.Id];
    }
    
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        DetailimageInformationModel *dInfoM = [[DetailimageInformationModel alloc]init];
        [dInfoM setValuesForKeysWithDictionary:object];
        dInfoM.data = [NSArray array];
        for (NSDictionary *dic in [object objectForKey:@"data"]) {
            DataModel *dataMo = [[DataModel alloc]init];
            [dataMo setValuesForKeysWithDictionary:dic];
            [self.dataSourceArray addObject:dataMo];
        }
        //_tabeleView.contentOffset = CGPointZero;
        [_tabeleView reloadData];
        [_tabeleView.header endRefreshing];
        [_tabeleView.footer endRefreshing];
        _HUD.hidden = YES;
        if (_dataSourceArray.count == 0) {
            _noticeLabel.text = @"没有想要的内容";
        }else{
            _noticeLabel.text = @"";
        }
        _pageLabel.text = [NSString stringWithFormat:@"第%ld页", _page];
    }];
    

}

#pragma mark 点击品牌筛选后 页面筛选为本品牌的 重载tableView
- (void)reloadPage:(ProductListModel *)PLM
{
    
    
    NSString *urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_List_V1&manuId=%@&noParam=1&num=20&page=%ld&priceId=noPrice&subcateId=%@", PLM.Id, _page, PLM.cateId];
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        DetailimageInformationModel *dinfoM = [[DetailimageInformationModel alloc]init];
        [dinfoM setValuesForKeysWithDictionary:object];
        NSArray *array = [object objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            DataModel *dataM = [[DataModel alloc]init];
            [dataM setValuesForKeysWithDictionary:dic];
            [self.dataSourceArray addObject:dataM];
        }
        //_tabeleView.contentOffset = CGPointZero;//可以避免重用tableView时不在顶格刷新的问题,在数据源清空时reloadtableView更优化
        ////NSLog(@"%@--%@", PLM.Id, PLM.cateId);
        //记录点击的是哪一个品牌
        self.manuidFlag = [NSString stringWithFormat:@"manuId=%@&", PLM.Id];
        [_tabeleView reloadData];
        _HUD.hidden = YES;
        if (_dataSourceArray.count == 0) {
            _noticeLabel.text = @"没有想要的内容";
        }else{
            _noticeLabel.text = @"";
        }
        [_tabeleView.header endRefreshing];
        [_tabeleView.footer endRefreshing];
        _pageLabel.text = [NSString stringWithFormat:@"第%ld页", _page];
    }];
    
}


#pragma mark 给产品cell赋值
-(void)setPLM:(ProductListModel *)PLM
{
    if (_PLM != PLM) {
        _PLM = PLM;
    }
    
}
























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
